package com.github.blanexie.nexusj.domain.peer

import com.github.blanexie.nexusj.infrastructure.repository.PeerRepository
import com.github.blanexie.nexusj.infrastructure.repository.impl.PeerDO
import java.util.stream.Collectors

class PeerDomainService(val repository: PeerRepository) {

    fun create(peerRequestCommand: PeerRequestCommand): PeerAggregate {
        return PeerAggregate(
            peerRequestCommand.peerId,
            peerRequestCommand.uploadedBytes,
            peerRequestCommand.downloadedBytes,
            peerRequestCommand.leftBytes,
            peerRequestCommand.uploadHost,
            peerRequestCommand.event,
            peerRequestCommand.numwant,
            0,
            peerRequestCommand.uploadTime,
            peerRequestCommand.uploadTime,
        )
    }

    fun upload(peerRequestCommand: PeerRequestCommand) {
        val peerAggregate = repository.findByPeerId(peerRequestCommand.peerId)
        peerAggregate!!.upload(
            peerRequestCommand.uploadedBytes,
            peerRequestCommand.downloadedBytes,
            peerRequestCommand.leftBytes,
            peerRequestCommand.uploadHost,
            peerRequestCommand.event,
            peerRequestCommand.numwant,
            peerRequestCommand.uploadTime
        )
    }

    /**
     * 获取活动的 peers
     */
    fun getActivePeers(infoHash: String, limit: Int): List<PeerDO> {
        val peerDOs = repository.findByInfoHash(infoHash)
        val collect = peerDOs.parallelStream()
            .sorted { o1, o2 -> if (o1.uploadedTime.isBefore(o2.uploadedTime)) 1 else -1 }
            .limit(limit.toLong())
            .collect(Collectors.toList())
        return collect
    }

    fun findByPeerId(peerId: PeerId): PeerAggregate? {
        return repository.findByPeerId(peerId)
    }

}